import axios from "axios";
import { getToken } from "@/utils/token";
import history from "../utils/history";
import { message } from "antd";
// import { removeToken } from "../utils/token";
import store from "../store";
import { logout } from "../store/actions/login";
//设置基准地址
const instance = axios.create({
  baseURL: "http://geek.itheima.net",
  timeout: 5000,
});

// 请求拦截器
instance.interceptors.request.use(
  function (config) {
    // 除了请求以外，其他请求统一添加token
    if (!config.url.startsWith("/v1_0/authorizations")) {
      config.headers.Authorization = "Bearer " + getToken();
    }
    return config;
  },
  function (error) {
    return Promise.reject(error);
  }
);

// 响应拦截器
instance.interceptors.response.use(
  function (response) {
    // 响应成功
    return response.data;
  },
  function (error) {
    // 处理网络超时
    if (!error.response) {
      message.error("网路繁忙，请稍后重试！");
    }
    console.log(error.response.status === 401);
    if (error.response && error.response.status === 401) {
      // 清理token
      store.dispatch(logout());
      // removeToken();
      // 退出登录
      // window.location.href = "/login"; //会刷新
      // history.go(0);
      // 给出消息
      message.error("登录超时");
      history.push("/login");
      history.go();
    }
  }
);

export default instance;
